import time
from selenium.webdriver.common.by import By
from common.Utils import BlogDriver


class BlogLogin:
    def __init__(self):
        self.url = "http://8.137.19.140:9090/blog_login.html"
        self.driver = BlogDriver.driver
        self.driver.get(self.url)

    def login(self, username, password):
        """通用登录方法"""
        self.driver.find_element(By.CSS_SELECTOR, "#username").clear()
        self.driver.find_element(By.CSS_SELECTOR, "#password").clear()

        self.driver.find_element(By.CSS_SELECTOR, "#username").send_keys(username)
        self.driver.find_element(By.CSS_SELECTOR, "#password").send_keys(password)
        self.driver.find_element(By.CSS_SELECTOR, "#submit").click()
        time.sleep(1)  # 等待页面加载

    def LoginSucTest(self):
        """成功登录测试"""
        self.login("zhangsan", "123456")

        try:
            # 验证登录成功元素
            nickname = self.driver.find_element(By.CSS_SELECTOR, "body > div.container > div.left > div > h3")
            print(f"登录成功! 用户昵称: {nickname.text}")
            BlogDriver.getScreeShot()
            return True
        except Exception as e:
            print("登录失败:", str(e))
            BlogDriver.getScreeShot()
            return False

    def LoginFailTest(self):
        """失败登录测试"""
        self.login("zhangsan", "12345")
        self.login("wangwu", "12345")
        self.login("wangwu", "123456")

        try:
            # 验证错误提示
            error_msg = self.driver.find_element(By.CSS_SELECTOR, "body").text
            print(f"登录失败提示: {error_msg}")
            BlogDriver.getScreeShot()
            assert "用户名或密码错误" in error_msg
            return True
        except Exception as e:
            print("失败测试未通过:", str(e))
            BlogDriver.getScreeShot()
            return False